#include "gathermgr.h"

#include "business_def.h"
#include "serialgchannel.h"
#include "netgchannel.h"
#include "nettchannel.h"
#include "serialtchannel.h"
#include "socket_gather.h"
#include "pfunc.h"
#include "Log.h"
#include "spaceMgr.h"
#ifdef WIN32
#define usleep(x) Sleep(x)
#endif
#ifdef __linux__
#ifndef sprintf_s
#define sprintf_s sprintf
#endif
#endif

#include "Log.h"

GatherMgr::GatherMgr()
{
	//
	acl::acl_cpp_init();
	//
	ptrBDef = BusinessDef::getInstance();
	CLogger::createInstance()->Log(MsgInfo
		, "app start and ComMDef init finish!");
	ptr_ToChannelDatas = QueueDataSingle<TransmitToGChannel>::getInstance();
	ptr_ToTranDatas = QueueDataSingle<ChannelToTransmit>::getInstance();
	initPort();
	//日志记录删除
	m_DiskSpaceMgr = new DiskSpaceMgr(ptrBDef->getDiskSymbol(),ptrBDef->getFreeSizeLimit()
		,ptrBDef->getLogDir(),"log");
	m_DiskSpaceMgr->start();
}

GatherMgr::~GatherMgr()
{
	std::map<int, TranChannel*>::iterator itnt = tchannel_map.begin();
	while (itnt != tchannel_map.end())
	{
		delete itnt->second;
		itnt->second = NULL;
#ifdef WIN32
		itnt = tchannel_map.erase(itnt);
#else
		// std::map<int, TranChannel*>::iterator ittemp = itnt++;
		// tchannel_map.erase(ittemp);
		tchannel_map.erase(itnt++);
#endif
	}

	std::map<int, GatherChannel*>::iterator itng = gchannel_map.begin();
	while (itng != gchannel_map.end())
	{
		delete itng->second;
		itng->second = NULL;
#ifdef WIN32
		itng = gchannel_map.erase(itng);
#else
		// std::map<int, GatherChannel*>::iterator ittemp = itng++;
		// gchannel_map.erase(ittemp);
		gchannel_map.erase(itng++);
#endif
	}
}

void GatherMgr::initPort()
{
	for (std::map<int,pyfree::Gather>::iterator it= ptrBDef->commdef.gathers.begin();
		it!=ptrBDef->commdef.gathers.end();++it)
	{
		//串口采集
		if (1==it->second.atts.channeltype)
		{
			std::map<int, pyfree::SerialPort>::iterator itp = ptrBDef->commdef.spdefs.find(it->second.atts.channelid);
			if (itp == ptrBDef->commdef.spdefs.end())
			{
				CLogger::createInstance()->Log(MsgError
					, "SerialGather(%d,%s) can't find SerialID(%d).[%s %s %d]"
					, it->second.atts.id, it->second.atts.name.c_str(), it->second.atts.channelid
					, __FILE__, __FUNCTION__, __LINE__);
				continue;
			}
			std::map<int, pyfree::ProtocolDef>::iterator itl = ptrBDef->commdef.protodefs.find(it->second.atts.protocolid);
			if (itl == ptrBDef->commdef.protodefs.end())
			{
				CLogger::createInstance()->Log(MsgError
					, "SerialGather(%d,%s) can't find protocolID(%d).[%s %s %d]"
					, it->second.atts.id, it->second.atts.name.c_str(), it->second.atts.protocolid
					, __FILE__, __FUNCTION__, __LINE__);
				continue;
			}
			SerialGChannel *sg_ptr = new SerialGChannel(it->second.atts.id);
			gchannel_map[it->second.atts.id] = sg_ptr;
			sg_ptr->start();
		}
		//网口采集
		if (2 == it->second.atts.channeltype)
		{
			std::map<int, pyfree::NetPort>::iterator itp = ptrBDef->commdef.netdefs.find(it->second.atts.channelid);
			if (itp == ptrBDef->commdef.netdefs.end())
			{
				CLogger::createInstance()->Log(MsgWarn
					, "NetGather(%d,%s) can't find NetID(%d).[%s %s %d]"
					, it->second.atts.id, it->second.atts.name.c_str(), it->second.atts.channelid
					, __FILE__, __FUNCTION__, __LINE__);
				continue;
			}
			std::map<int, pyfree::ProtocolDef>::iterator itl = ptrBDef->commdef.protodefs.find(it->second.atts.protocolid);
			if (itl == ptrBDef->commdef.protodefs.end())
			{
				CLogger::createInstance()->Log(MsgWarn
					, "NetGather(%d,%s) can't find protocolID(%d).[%s %s %d]"
					, it->second.atts.id, it->second.atts.name.c_str(), it->second.atts.protocolid
					, __FILE__, __FUNCTION__, __LINE__);
				continue;
			}
			NetGChannel* ngp = new NetGChannel(it->second.atts.id);
			gchannel_map[it->second.atts.id] = ngp;
			ngp->start();
		}
		//网口级联
		if (3 == it->second.atts.channeltype)
		{
			std::map<int, pyfree::NetPort>::iterator itp = ptrBDef->commdef.netdefs.find(it->second.atts.channelid);
			if (itp == ptrBDef->commdef.netdefs.end())
			{
				CLogger::createInstance()->Log(MsgError
					, "NetGatherGX(%d,%s) can't find NetID(%d).[%s %s %d]"
					, it->second.atts.id, it->second.atts.name.c_str(), it->second.atts.channelid
					, __FILE__, __FUNCTION__, __LINE__);
				continue;
			}
			std::map<int, pyfree::ProtocolDef>::iterator itl = ptrBDef->commdef.protodefs.find(it->second.atts.protocolid);
			if (itl == ptrBDef->commdef.protodefs.end())
			{
				CLogger::createInstance()->Log(MsgError
					, "NetGatherGX(%d,%s) can't find protocolID(%d).[%s %s %d]"
					, it->second.atts.id, it->second.atts.name.c_str(), it->second.atts.protocolid
					, __FILE__, __FUNCTION__, __LINE__);
				continue;
			}
			//
			SocketGather *sg_ptr = new SocketGather(it->second.atts.id);
			gchannel_map[it->second.atts.id] = sg_ptr;
		}
	}
	for (std::map<int,pyfree::Transmit>::iterator it = ptrBDef->commdef.trans.begin();
		it != ptrBDef->commdef.trans.end();++it)
	{
		//串口转发
		if (it->second.channeltype== 1)
		{
			std::map<int, pyfree::SerialPort>::iterator itp = ptrBDef->commdef.spdefs.find(it->second.channelid);
			if (itp == ptrBDef->commdef.spdefs.end())
			{
				CLogger::createInstance()->Log(MsgError
					, "SerialTran(%d,%s) can't find SerialID(%d).[%s %s %d]"
					, it->first, it->second.name.c_str(), it->second.channelid
					, __FILE__, __FUNCTION__, __LINE__);
				continue;
			}
			std::map<int, pyfree::ProtocolDef>::iterator itl = ptrBDef->commdef.protodefs.find(it->second.protocolid);
			if (itl == ptrBDef->commdef.protodefs.end())
			{
				CLogger::createInstance()->Log(MsgError,
				"the Serial(%d,%s)config for protocoltype[%d] error, no map protocol define"
				",please check it,[%s %s %d]!"
				, it->first, it->second.name.c_str(), it->second.protocolid
				, __FILE__, __FUNCTION__, __LINE__);
				continue;
			}
			SerialTChannel *stchannel = new SerialTChannel(it->first);
			tchannel_map[it->first] = stchannel;
			stchannel->start();
		}
		//网络转发
		if (it->second.channeltype == 2)
		{
			//转发口编号
			std::map<int, pyfree::NetPort>::iterator itp = ptrBDef->commdef.netdefs.find(it->second.channelid);
			if (itp == ptrBDef->commdef.netdefs.end())
			{
				CLogger::createInstance()->Log(MsgError
					, "NetTran(%d) can't find NetID(%d).[%s %s %d]"
					, it->first, it->second.channelid
					, __FILE__, __FUNCTION__, __LINE__);
				continue;
			}
			//自定义解析脚本
			if (1==itp->second.type)
			{
				std::map<int, pyfree::ProtocolDef>::iterator itl = ptrBDef->commdef.protodefs.find(it->second.protocolid);
				if (itl == ptrBDef->commdef.protodefs.end())
				{
					CLogger::createInstance()->Log(MsgError,
					"the client[%d] ip[%s] port[%d] config for protocoltype[%d] error, no map protocol define"
					",please check it,[%s %s %d]!"
					, it->first, itp->second.ip.c_str(), itp->second.port, it->second.protocolid
					, __FILE__, __FUNCTION__, __LINE__);
					continue;
				}
			}
			//2==itp->second.type,程序内定义了解析,无需加载脚本
			if (pyfree::ipCheck(itp->second.ip))
			{
				NetTChannel *ntp = new NetTChannel(it->first);
				tchannel_map[it->first] = ntp;
				ntp->start();
			}
			else
			{
				CLogger::createInstance()->Log(MsgError,
					"the client[%d] ip[%s] port[%d] config error,please check it,[%s %s %d]!"
					, it->first, itp->second.ip.c_str(), itp->second.port
					, __FILE__, __FUNCTION__, __LINE__);
			}
		}
	}
}

void* GatherMgr::run()
{
	TransmitToGChannel item_r;
	pyfree::PFrom _pf;
	ChannelToTransmit item_s;
	while (true)
	{
		//获取转发服务端下发的数据
		if (ptr_ToChannelDatas->pop(item_r))
		{
			CLogger::createInstance()->Log(MsgInfo,
				"TaskID[%lu] and down_node[3] getFirstRDS,time(%s)"
				",exeType(%d),pID(%d),pType(%d),val(%.3f)"
				, item_r.taskID, pyfree::getCurrentTime().c_str()
				, static_cast<int>(item_r.exeType), item_r.pID
				, static_cast<int>(item_r.pType), item_r.val);
			if (ptrBDef->getPFrom(item_r.pID, item_r.pType,_pf))
			{
				//分发到指定采集端口
				std::map<int, GatherChannel*>::iterator it = gchannel_map.find(_pf.gid);
				if (it != gchannel_map.end())
				{
					it->second->downControl(static_cast<int>(item_r.exeType), _pf.ptype, _pf.pid, item_r.val, item_r.taskID);
				}
			}
		}
		//将数据分发到各个转发线程
		if (ptr_ToTranDatas->pop(item_s))
		{
			if (item_s.changeF&&item_s.taskID>0) 
			{
				CLogger::createInstance()->Log(MsgInfo,
					"TaskID[%lu] and up_node[3] ToTranData getFirst data,time(%s)"
					",pID(%d),pType(%d),val(%.3f)"
					, item_s.taskID, pyfree::getCurrentTime().c_str()
					, item_s.pID, static_cast<int>(item_s.pType), item_s.val);
			}
			for (std::map<int, TranChannel*>::iterator it = tchannel_map.begin(); it != tchannel_map.end(); ++it)
			{
				if(NULL!=it->second)
					it->second->add(item_s);
			}
		}
		usleep(1);
	}
	return NULL;
}
